package net.wicp.tams.common.binlog.self.bean;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;

import lombok.Builder;
import lombok.Data;
import net.wicp.tams.common.binlog.self.callback.ICol;
import net.wicp.tams.common.constant.OptType;
import net.wicp.tams.common.binlog.self.proto.SendObjProto;
import net.wicp.tams.common.binlog.self.proto.SendObjProto.Col;
import net.wicp.tams.common.binlog.self.proto.SendObjProto.Col.ColumnType;

/***
 * 给发送者的数据封装
 * 
 * @author zhoujunhui
 *
 */
@Data
@Builder
public class SendBean {
	private TableMapBean tableMapBean;
	private int columnCount;
	private OptType optType;// 操作类型
	private long timestamp;// 事件头里的时间戳
	private String gtid;

	private List<SendRow> rows;

	public SendObj toSendObj() {
		SendObj retobj = SendObj.builder().optType(optType).rows(rows).gtid(gtid).db(tableMapBean.getSchemaName())
				.tb(tableMapBean.getTableName()).build();
		return retobj;
	}

	public net.wicp.tams.common.binlog.self.proto.SendObjProto.SendObj toProto() {
		net.wicp.tams.common.binlog.self.proto.SendObjProto.SendObj.Builder sendobj = SendObjProto.SendObj.newBuilder();
		sendobj.setOptType(
				Enum.valueOf(net.wicp.tams.common.binlog.self.proto.SendObjProto.SendObj.OptType.class, optType.name()));
		List<net.wicp.tams.common.binlog.self.proto.SendObjProto.SendRow> protoRows = new ArrayList<>();
		for (SendRow ele : rows) {
			net.wicp.tams.common.binlog.self.proto.SendObjProto.SendRow.Builder insertemp = net.wicp.tams.common.binlog.self.proto.SendObjProto.SendRow
					.newBuilder();
			convertRow(ele, true, insertemp);
			convertRow(ele, false, insertemp);
			protoRows.add(insertemp.build());
		}

		sendobj.addAllRows(protoRows);
		sendobj.setGtid(gtid);
		sendobj.setDb(tableMapBean.getSchemaName());
		sendobj.setTb(tableMapBean.getTableName());
		net.wicp.tams.common.binlog.self.proto.SendObjProto.SendObj ret = sendobj.build();
		return ret;
	}

	@SuppressWarnings("rawtypes")
	private void convertRow(SendRow ele, boolean isBefore,
			net.wicp.tams.common.binlog.self.proto.SendObjProto.SendRow.Builder insertemp) {
		List<ICol> templist = isBefore ? ele.getBefore() : ele.getAfter();
		if (CollectionUtils.isNotEmpty(templist)) {
			List<Col> tempInsert = new ArrayList<>();
			for (ICol iCol : templist) {
				Col.Builder colbuilder = Col.newBuilder();
				colbuilder.setColName(iCol.getColName());
				colbuilder.setColType(Enum.valueOf(ColumnType.class, iCol.getColType().name()));
				colbuilder.setValue(iCol.getClient());
				tempInsert.add(colbuilder.build());
			}
			if (isBefore) {
				insertemp.addAllBefore(tempInsert);
			} else {
				insertemp.addAllAfter(tempInsert);
			}
		}
	}

}
